package com.pdweb.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.pdweb.dao.EmpresasDao;
import com.pdweb.dao.UsuariosDao;
import com.pdweb.vo.Usuarios;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doService(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doService(request, response);

	}

	protected void doService(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {

			HttpSession session = request.getSession();

			Usuarios usuarios = new Usuarios();

			usuarios.setLogin(request.getParameter("ST_LOGIN_USR"));
			usuarios.setSenha(request.getParameter("ST_PASSWORD_USR"));

			UsuariosDao usuariosDao = new UsuariosDao();

			usuarios = usuariosDao.verificaLogin(usuarios);

			if (usuarios != null) {
				
				EmpresasDao empresasDao = new EmpresasDao();
				
				boolean teste = empresasDao.verificaEmpresa();
				
				if(teste == false){
					session.setAttribute("user", usuarios);
					request.setAttribute("empresaVazio", teste);
					
				   

					getServletContext().getRequestDispatcher("/PerfilServlet").forward(
							request, response);

				} else {
					session.setAttribute("user", usuarios);

					getServletContext().getRequestDispatcher("/PerfilServlet")
							.forward(request, response);

				}

			} else {

				request.setAttribute("erro", "senha ou usuario invalido");
				getServletContext().getRequestDispatcher("/login.jsp").forward(
						request, response);
			}

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
